import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend

from .models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 手机号登录
            user = User.objects.get(mobile=account)
        else:
            # 用户名登录
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法，实现多账号登录
        :param request: 请求对象
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数
        :return: user
        """
        # 根据传入的user
        # name获取user对象。username可以是手机号也可以是账号
        if request is None:
            try:
                user = User.objects.get(username=username, is_staff=True)
            except:
                return None
        #     判断密码
            if user.check_password(password):
                return user
        else:
            user = get_user_by_account(username)
            # 校验user是否存在并校验密码是否正确
            if user and user.check_password(password):
                return user


def generate_verify_email_url(user):
    data_dict = {'user_id': user.id, 'email': user.email}
    from utils.scert import SecretOauth
    secret_data = SecretOauth().dumps(data_dict)
    active_url = settings.EMAIL_ACTIVE_URL + '?token=' + secret_data
    return active_url


# 封装加密和揭秘
import pickle
import base64


class CookieSecret(object):
    # 加密
    @classmethod
    def dumps(cls, data):
        # 1.将数据装换成bytes
        data_bytes = pickle.dumps(data)
        # 2.将bytes使用base64序列化加密
        base64_bytes = base64.b64encode(data_bytes)
        # 3.将加密完毕的bytes以字符串类型输出
        base64_str = base64_bytes.decode()
        return base64_str

    # 解密
    @classmethod
    def loads(cls, data):
        # 1.将数据解密转成bytes
        base64_bytes = base64.b64decode(data)
        # 2.将bytes转回原来的python类型
        pickle_data = pickle.loads(base64_bytes)
        return pickle_data
